package main

import (
	"log"
	"math/rand"
	"sync"
	"time"
)

func init() {
	// 我们一般使用系统时间的不确定性来进行初始化
	rand.Seed(time.Now().UnixNano())
	log.SetPrefix("TRACE: ")
	log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
}

var (
	lock    sync.Mutex
	wg      sync.WaitGroup
	intChan = make(chan int)
)

//程序的入口
func main() {

	go collectIntToChan()
	printInt(intChan)
	wg.Wait()
}

func collectIntToChan() {
	for i := 0; i < 50; i++ {
		time.Sleep(time.Duration(rand.Intn(1)) * time.Second)
		log.Println("输入", i)
		intChan <- i
	}
	close(intChan)

}
func printInt(picChan <-chan int) {
	for {
		if data, ok := <-picChan; ok {
			wg.Add(1)
			go printSleep(data)
		} else {
			break
		}
	}
}
func printSleep(data int) {
	defer wg.Done()
	time.Sleep(time.Duration(rand.Intn(1000)) * time.Millisecond)
	log.Println("输出", data)
}
